
/*
 *  This program is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation, either version 3 of the License, or
 *  (at your option) any later version.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */


#include <stdio.h>

#include "libmooigraph.h"
#include "lmg.h"

static void lmg_1nal (struct lmgnodel *nl);
static void lmg_initx (void);

void
lmg_levels (void)
{
  struct lmgnodel *ptr;
  lmgnal = lmg_malloc ((lmgnlevels + 1) * sizeof (int));
  lmglevels = lmg_malloc ((lmgnlevels + 1) * sizeof (struct lmgnodel *));
  ptr = lmgnodelist;
  while (ptr)
    {
      lmg_1nal (ptr);
      ptr = ptr->next;
    }
  lmg_initx ();
  return;
}

void
lmg_levelsclear (void)
{
  int i;
  struct lmgnodel *ptr;
  struct lmgnodel *ptr2;
  for (i = 0; i < lmgnlevels; i++)
    {
      ptr = lmglevels[i];
      while (ptr)
	{
	  ptr2 = ptr->next;
	  lmg_free (ptr);
	  ptr = ptr2;
	}
    }
  lmg_free (lmglevels);
  lmg_free (lmgnal);
  return;
}

static void
lmg_1nal (struct lmgnodel *nl)
{
  struct lmgnode *node;
  int level;
  struct lmgnodel *nal;
  struct lmgnodel *ptr;
  node = nl->node;
  level = node->tree_layout.level;
  nal = lmg_malloc (sizeof (struct lmgnodel));
  nal->node = node;
  if (lmglevels[level])
    {
      ptr = lmglevels[level];
      while (ptr)
	{
	  if (ptr->next == NULL)
	    {
	      break;
	    }
	  ptr = ptr->next;
	}
      ptr->next = nal;
    }
  else
    {
      lmglevels[level] = nal;
    }
  return;
}

static void
lmg_initx (void)
{
  int i;
  int pos;
  struct lmgnodel *ptr;
  for (i = 0; i < lmgnlevels; i++)
    {
      pos = 0;
      ptr = lmglevels[i];
      while (ptr)
	{
	  ptr->node->tree_layout.position = pos;
	  pos = pos + 1;
	  ptr = ptr->next;
	}
      lmgnal[i] = pos;
    }
  return;
}

int
lmg_nnal (int level)
{
  struct lmgnodel *ptr;
  int i;
  ptr = lmglevels[level];
  if (ptr == NULL)
    {
      return (0);
    }
  i = 0;
  while (ptr)
    {
      i = i + 1;
      ptr = ptr->next;
    }
  return (i);
}

/* End */
